package com.risen.service;


import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.risen.bean.User;
import com.risen.dao.UserMapper;
import com.risen.exception.UserException;
import com.risen.util.DateUtils;
import com.risen.util.MailUtils;
import com.risen.util.UUIDGenerator;

/**
 * @author sen
 *	用户注册的service层
 */
@Service
public class UserService {
	
	@Resource
	private UserMapper userMapper;
	
	//md5盐值,用于混淆md5
	private final String slat = "dfewqr324*&^%$*$ghyuhfe3432fe46";
	
	
	/**
	 * @param loginname
	 * @return
	 *  用户名是否已被注册
	 */
	public boolean validateLoginname(String loginname) {
		return userMapper.validateLoginname(loginname)==0;
	}
	
	
	/**
	 * @param email
	 * @return
	 *  邮箱是否已被注册
	 */
	public boolean validateEmail(String email) {
		return userMapper.validateEmail(email)==0;
	}
	
	/**
	 * 新增用户
	 */
	public User addUser(User user){
		/*
		 * 1.补齐表单没有的数据
		 */
		user.setStatus(false);//设置状态为未激活
		user.setUid(UUIDGenerator.getShort()+UUIDGenerator.getShort());//生成16位uid
		user.setActivationCode(UUIDGenerator.getLong()+UUIDGenerator.getLong());//生成64位激活码
		/*
		 * 2.向数据库添加数据,给密码加密
		 */
		String password = getMD5(user.getLoginpass());
		user.setLoginpass(password);
		userMapper.addUser(user);
		/*
		 * 3.给用户发送激活邮件
		 */
		sendEmail(user);
		
		return user;
	}
	
	/**
	 * 给用户发邮件
	 */
	public void sendEmail(User user){
		//把配置文件内容封装到Properties对象中
		Properties prop=new Properties();
		try {   //javaMail.properties位于classpath下
			prop.load(this.getClass().getClassLoader().getResourceAsStream("javaMail.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		//获取用户邮箱地址
		String to=user.getEmail();
		//设置邮件内容，将模板文件的占位符替换
		String content=MessageFormat.format(prop.getProperty("javaMail.content"), user.getActivationCode());
		//修改prop对象
		prop.setProperty("javaMail.content", content);
		//发送邮件
		try {
			MailUtils.sendEmail(prop, to);
		} catch (Exception e) {
			e.printStackTrace();
		}
				
	}
	
	/**
	 *  注册激活的service层方法
	 * @throws UserException 
	 */
	public User activate(String urlActivationCode) throws UserException{
		//按照激活码查询，判断User对象是否为空，如果为空，为无效激活码，抛出异常
		
		User user=userMapper.queryByActivationCode(urlActivationCode);
		if(user==null){
			throw new UserException("invalid");
		//如果status为true，用户已经激活过了
		}else if(user.getStatus()){
			throw new UserException("havedone");
		}
		
		//调用dao设置status完成激活
		userMapper.updateStatus(user.getUid());
		return user;
	}
	
	/**
	 * 用户登录的service层方法
	 */
	public User doLogin(Map<String,String> loginMap){
		//密码加密处理
		String password = loginMap.get("password");
		loginMap.put("password", getMD5(password));
		return userMapper.doLogin(loginMap);
	}

	/**
	 * @param map
	 *  用户修改密码的service层方法
	 */
	public void updateLoginpass(Map<String, String> map) {
		//密码加密处理
		String password = map.get("password");
		map.put("password", getMD5(password));
		userMapper.updateLoginpass(map);
	}
	
	public String findUserByName(String loginname) {
		return userMapper.findUserByName(loginname);
	}
	
	/**
	 * 根据id得到md5值
	 * @param seckillId
	 * @return
	 */
	private String getMD5(String loginpass){
		String base = loginpass + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes()); //spring提供的工具类生成md5
		System.out.println(md5);
		return md5;
	}
	
	public Map<String, Object> findUser(Map<String, Object> param) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("data", userMapper.findUser(param));
		return result;
	}
	
	/**
	 * 管理员更新用户数据
	 * @param user
	 */
	//@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
	public boolean updateUserAd(User user) {
		try {
			String password = user.getLoginpass();
			if (password != null && !"".equals(password)) {
				password = getMD5(password);
				user.setLoginpass(password);
			}
			userMapper.updateUserAd(user);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 管理员新增用户
	 * @param user
	 */
	//@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
	public boolean insertUserAd(User user) {
		try {
			String password = user.getLoginpass();
			if (password != null && !"".equals(password)) {
				password = getMD5(password);
				user.setLoginpass(password);
			}
			String addTime = DateUtils.getNowTime();
			String uid = UUIDGenerator.getLong();
			user.setAddTime(addTime);
			user.setUid(uid);
			user.setLevel("普通会员");
			userMapper.insertUserAd(user);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 管理员删除用户
	 * @param user
	 */
	//@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
	public boolean delUserById(String uid) {
		try {
			userMapper.delUserById(uid);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
}
